package base.core.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * @Description
 * @Author Pengwei
 * @CreatDate 2021/11/14 14:53
 */
public class Utils {

    /**
     * 通过{}拼接字符串
     */
    public static String format(String str, Object... args) {
        if (args == null || args.length == 0) {
            return str;
        }
        for (Object arg : args) {
            if (arg == null) {
                arg = "";
            }
            str = str.replaceFirst("\\{\\}", arg.toString());
        }
        return str;
    }

    /**
     * 获取填位符
     *
     * @param space 填充的字符串
     * @param index 填充的数量
     * @return
     */
    public static String getSpace(String space, int index) {
        StringBuilder builder = new StringBuilder();
        space = StringUtils.isBlank(space) ? "" : space;
        for (int i = 0; i < index; i++) {
            builder.append(space);
        }
        return builder.toString();
    }

    /**
     * 获取文件的后缀
     * abc.zip -> zip
     * a.b.c.zip -> zip
     * abc -> ''
     * .abc -> abc
     * abc. -> ''
     * @param fileName
     * @return
     */
    public static String getFileSuffix(String fileName) {
        int index = fileName.lastIndexOf(".");
        if (index < 0) {
            return "";
        }
        String suffix = fileName.substring(index + 1);
        return suffix;
    }

    public static HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    public static HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        return response;
    }

    public static void main(String[] args) {
        System.out.println(getSpace(null, 10));
    }
}
